package com.example.parallelandroid;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;

import android.text.TextUtils;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.example.parallelandroid.entity.UserInfo;
import com.example.parallelandroid.utils.BitmapUtils;
import com.example.parallelandroid.utils.CameraUtils;
import com.example.parallelandroid.utils.CustomDatePicker;
import com.example.parallelandroid.utils.SPUtils;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.imageview.ShapeableImageView;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

//用户更新个人信息
public class UpdatePersonActivity extends AppCompatActivity {
    //权限请求
    private RxPermissions rxPermissions;

    //是否拥有权限
    private boolean hasPermissions = false;

    //底部弹窗
    private BottomSheetDialog bottomSheetDialog;
    //弹窗视图
    private View bottomView;

    //启动相册标识
    public static final int SELECT_PHOTO = 2;

    //图片控件
    private ShapeableImageView ivHead,ivPaihangHead;
    //Base64
    private String base64Pic;
    //拍照和相册获取图片的Bitmap
    private Bitmap orc_bitmap;

    //Glide请求图片选项配置
    private RequestOptions requestOptions = RequestOptions.circleCropTransform()
            .diskCacheStrategy(DiskCacheStrategy.NONE)//不做磁盘缓存
            .skipMemoryCache(true);//不做内存缓存

    //接收页面跳转携带信息
    private UserInfo userInfo;
    private SharedPreferences user;

    private String userId;

    //控件
    private LinearLayout paihang;
    private Toolbar toolbar;
    private RadioGroup rgGroup;
    private RadioButton rbMale,rbFemale;
    private EditText edtName,edtIntrodece;
    private Button updatePerson;
    private String provinceValue,gender;
    private int paihangPos;

    private MyPopupWindow popupwindow;

    private String xingbie;
    private String[] array;

    //与生日选择有关
    private RelativeLayout selectDate;
    private TextView currentDate;
    private CustomDatePicker datePicker;
    private String time;
    private String date;
    private String oldbir;
    //存下dialog选择的生日的字符串
    private String birthday;
    private int index;

    private SharedPreferences.Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_person);

        // 获取SharedPreferences
        user = getSharedPreferences("user", MODE_PRIVATE);
        userId = user.getString("userId", "userId");

        //获取控件对象
        //获取控件对象
        Spinner spinner = (Spinner) findViewById(R.id.provincespinner);
        //下拉框
        array = new String[]{"河北省","山西省","辽宁省","吉林省","黑龙江省",
                "江苏省","浙江省","安徽省","福建省","江西省","山东省","河南省","湖北省","湖南省","广东省",
                "海南省","四川省","贵州省","云南省","陕西省","甘肃省","青海省","台湾省","内蒙古自治区","广西壮族自治区",
                "西藏自治区","宁夏回族自治区","新疆维吾尔自治区","北京市","上海市","天津市","重庆市","香港特别行政区","澳门特别行政区"};
        ivHead = findViewById(R.id.iv_head);
        ivPaihangHead = findViewById(R.id.iv_paihanghead);
        paihang = findViewById(R.id.paihang);
        rgGroup = findViewById(R.id.rg_group);
        rbMale = findViewById(R.id.rb_male);
        rbFemale = findViewById(R.id.rb_female);
        edtName = findViewById(R.id.edt_name);
        edtIntrodece = findViewById(R.id.edt_introduce);
        updatePerson = findViewById(R.id.btn_updateperson);
        toolbar = findViewById(R.id.updatetoolbar);
        selectDate = (RelativeLayout) findViewById(R.id.selectDate);
        selectDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 日期格式为yyyy-MM-dd
                datePicker.show(date);
            }
        });
        currentDate = (TextView) findViewById(R.id.currentDate);
        initPicker();

        edtName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String pwd = edtName.getText().toString();
                if(TextUtils.isEmpty(pwd)&&"".equals(pwd)){
                    edtName.setError("请输入昵称");
                }else {
                    if(pwd.length()>0&&pwd.length()<=15){

                    }else {
                        edtName.setError("最长15字符");

                    }
                }
            }
        });

        // 为ToolBar添加返回键
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true); // 添加默认的返回图标
        getSupportActionBar().setHomeButtonEnabled(true); // 设置返回键可用
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish(); // 返回
            }
        });



        //页面跳转携带数据
        Intent intent = this.getIntent();
        userInfo= (UserInfo) intent.getSerializableExtra("userinfo");
        String paihangImg = userInfo.getAvatar();
        Glide.with(this).load(getUrl(paihangImg)).apply(requestOptions).into(ivPaihangHead);
        String name = userInfo.getNickName();
        String introduce = userInfo.getBio();
        String shengfen = userInfo.getProvince();
        Constant.logger.info(shengfen);
        //遍历数组 找到省份对应下标
        for(int i=0;i<array.length;i++){
            if(array[i].equals(shengfen)){
                index=i;
                break;
            }
        }
        //设置成下标对应的省份值
        spinner.post(new Runnable(){
            @Override
            public void run(){
                spinner.setSelection(index);
            }
        });

        //获取生日默认显示
        if(userInfo.getBirthday()!=null){
            oldbir = userInfo.getBirthday().toString();
            currentDate.setText(oldbir);
        }else{//用户第一次登录没选生日 默认置为0000-00-00
            currentDate.setText("0000-00-00");
        }
        //获取性别默认选中
        xingbie = userInfo.getGender();
        if (TextUtils.isEmpty(xingbie)){
            xingbie = "未知";
        }else if(xingbie.equals("女")){
            rbFemale.setChecked(true);
        }else{
            rbMale.setChecked(true);
        }
        edtName.setText(name);
        edtIntrodece.setText(introduce);

        //检查版本
        checkVersion();

        //取出缓存
        String imageUrl = SPUtils.getString("imageUrl"+userId,null,this);
        if(imageUrl != null){
            Glide.with(this).load(imageUrl).apply(requestOptions).into(ivHead);
        }

        // 创建适配器
        final ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(UpdatePersonActivity.this, R.layout.spinner_item, array);
        dataAdapter.setDropDownViewResource(R.layout.spinner_item);
        // 为下拉列表框设置适配器
        spinner.setAdapter(dataAdapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                provinceValue = dataAdapter.getItem(position).toString();// 获取被选中的下拉列表框项的值
                //Toast.makeText(UpdatePersonActivity.this, "你选中了：" + provinceValue, Toast.LENGTH_SHORT).show();

            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // 没有任何被选中的处理事件
            }
        });

        updatePerson.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updateUserInfo2Server();
                Intent newIntent = new Intent(UpdatePersonActivity.this,MainFromActivity.class);
                startActivity(newIntent);
                finish();
                Toast.makeText(UpdatePersonActivity.this, "修改个人资料成功！", Toast.LENGTH_SHORT).show();
            }
        });

        //获取选中的性别
        rgGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                selectRadioButton();
            }
        });

        //点击排行榜头像弹出popupwindow
        paihang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupwindow=new MyPopupWindow(UpdatePersonActivity.this);
                popupwindow.showAsDropDown(v, 100, -300);//显示的位置
                popupwindow.setYesOnclickListener(new MyPopupWindow.onYesOnclickListener() {
                    @Override
                    public void onYesOnclick() {
                        paihangPos =SPUtils.getInt("paihangImg",0,UpdatePersonActivity.this);
                        //Toast.makeText(UpdatePersonActivity.this, ""+paihangPos, Toast.LENGTH_SHORT).show();
                        Glide.with(UpdatePersonActivity.this).load(getUrl(paihangPos+"")).apply(requestOptions).into(ivPaihangHead);
                    }
                });

            }
        });
    }

    private void initPicker() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        time = sdf.format(new Date());
        date = time.split(" ")[0];

        /**
         * 设置年月日
         */
        datePicker = new CustomDatePicker(this, "请选择日期", new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) {
                currentDate.setText(time.split(" ")[0]);
                birthday = currentDate.getText().toString();
            }
        }, "1920-01-01 00:00", time);
        datePicker.showSpecificTime(false); //显示时和分
        datePicker.setIsLoop(false);
        datePicker.setDayIsLoop(true);
        datePicker.setMonIsLoop(true);
    }

    private void checkVersion() {
        //Android6.0及以上版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //如果你是在Fragment中，则把this换成getActivity()
            rxPermissions = new RxPermissions(this);
            //权限请求
            rxPermissions.request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .subscribe(granted -> {
                        if (granted) {//申请成功
                            Constant.logger.info("获取权限: 已获取相册权限");
                            //showMsg("已获取权限");
                            hasPermissions = true;
                        } else {//申请失败
                            Constant.logger.warn("获取权限: 相册权限未开启");
                            showMsg("权限未开启,请前往设置打开权限");
                            hasPermissions = false;
                        }
                    });
        } else {
            //Android6.0以下
            showMsg("无需请求动态权限");
        }
    }

    //获取选中的性别值
    private void selectRadioButton() {
        //通过radioGroup.getCheckedRadioButtonId()来得到选中的RadioButton的ID，从而得到RadioButton进而获取选中值
        RadioButton rb = (RadioButton)UpdatePersonActivity.this.findViewById(rgGroup.getCheckedRadioButtonId());
        gender = (String) rb.getText();
        //Toast.makeText(UpdatePersonActivity.this, "你选中了：" + gender, Toast.LENGTH_SHORT).show();
    }

    /**
     * 更换头像
     * @param view
     */
    public void changeAvatar(View view) {
        bottomSheetDialog = new BottomSheetDialog(this);
        bottomView = getLayoutInflater().inflate(R.layout.dialog_bottom, null);
        bottomSheetDialog.setContentView(bottomView);
        bottomSheetDialog.getWindow().findViewById(R.id.design_bottom_sheet).setBackgroundColor(Color.TRANSPARENT);
        TextView tvOpenAlbum = bottomView.findViewById(R.id.tv_open_album);
        TextView tvCancel = bottomView.findViewById(R.id.tv_cancel);

        //打开相册
        tvOpenAlbum.setOnClickListener(v -> {
            openAlbum();
            showMsg("打开相册");
            bottomSheetDialog.cancel();
        });
        //取消
        tvCancel.setOnClickListener(v -> {
            bottomSheetDialog.cancel();
        });
        //底部弹窗显示
        bottomSheetDialog.show();
    }
    /**
     * 打开相册
     */
    private void openAlbum() {
        if (!hasPermissions) {
            showMsg("未获取到权限");
            checkVersion();
            return;
        }
        startActivityForResult(CameraUtils.getSelectPhotoIntent(), SELECT_PHOTO);
    }

    /**
     * 返回到Activity
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case SELECT_PHOTO:
                if (resultCode == RESULT_OK) {
                    String imagePath = null;
                    //判断手机系统版本号
                    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
                        //4.4及以上系统使用这个方法处理图片
                        imagePath = CameraUtils.getImageOnKitKatPath(data, this);
                    } else {
                        imagePath = CameraUtils.getImageBeforeKitKatPath(data, this);
                    }
                    //显示图片
                    displayImage(imagePath);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 通过图片路径显示图片
     */
    private void displayImage(String imagePath) {
        if (!TextUtils.isEmpty(imagePath)) {

            //放入缓存
            SPUtils.putString("imageUrl"+userId,imagePath,this);

            //显示图片
            Glide.with(this).load(imagePath).apply(requestOptions).into(ivHead);

            //压缩图片
            orc_bitmap = CameraUtils.compression(BitmapFactory.decodeFile(imagePath));
            //转Base64
            base64Pic = BitmapUtils.bitmapToBase64(orc_bitmap);

        } else {
            showMsg("图片获取失败");
        }
    }

    public static java.sql.Date strToDate(String str) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");	// 使用给定模式yyyy-MM-dd
        java.util.Date udate = format.parse(str);		// 从字符串中解析文本以产生一个java.util.Date
        java.sql.Date sdate = new java.sql.Date(udate.getTime());	// getTime()获取时间戳，再用构造方法构造
        return sdate;
    }


    /**
     * Toast提示
     *
     * @param msg
     */
    private void showMsg(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }
    //更改数据库中的值
    private void updateUserInfo2Server() {
        OkHttpClient okHttpClient = new OkHttpClient();
        UserInfo newUserInfo = new UserInfo();
        newUserInfo = userInfo;
        newUserInfo.setNickName(edtName.getText().toString());
        newUserInfo.setBio(edtIntrodece.getText().toString());
        newUserInfo.setProvince(provinceValue);
        if (TextUtils.isEmpty(gender)){
            newUserInfo.setGender(xingbie);
        }else{
            newUserInfo.setGender(gender);
        }
        if (paihangPos==0){
            newUserInfo.setAvatar(userInfo.getAvatar());
        }else{
            newUserInfo.setAvatar(paihangPos+"");
        }
        if (TextUtils.isEmpty(birthday)){
            newUserInfo.setBirthday(userInfo.getBirthday());
        }else{
            try {
                newUserInfo.setBirthday(strToDate(birthday));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        GsonBuilder builder = new GsonBuilder().setDateFormat("yyyy-MM-dd");
        builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
            public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
                return new Date(json.getAsJsonPrimitive().getAsLong());
            }
        });
        Gson gson = builder.create();
        String json = gson.toJson(newUserInfo);

        Constant.logger.info("开始向服务端传输用户个人信息数据userInfo userId=" + newUserInfo.toString());

        //创建一个RequestBody(参数1：数据类型 参数2传递的json串)
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);

        //创建请求对象（Request）
        Request request = new Request.Builder()
                .url(Constant.BASE_URL+"userInfo/createUserInfo")
                .post(requestBody)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Constant.logger.warn("向服务端传输用户个人信息数据: 失败", e);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String json = response.body().string();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(json);
                    String msg = jsonObject.getString("msg");
                    Constant.logger.info("服务端Response: " + msg);

                    editor = user.edit();
                    editor.putString("userProvince",provinceValue);
                    editor.putString("nickName",edtName.getText().toString());
                    editor.putString("userBio",edtIntrodece.getText().toString());
                    editor.commit();

                } catch (JSONException e) {
                    Constant.logger.warn("解析服务端Response: 失败", e);
                }
            }
        });
    }

    //获取头像
    private int getUrl(String pos){
        int newurl = 0;
        switch(pos){
            case "1":
                newurl = R.mipmap.tou1;
                break;
            case "2":
                newurl = R.mipmap.tou2;
                break;
            case "3":
                newurl = R.mipmap.tou3;
                break;
            case "4":
                newurl = R.mipmap.tou4;
                break;
            case "5":
                newurl = R.mipmap.tou5;
                break;
            case "6":
                newurl = R.mipmap.tou6;
                break;
            case "7":
                newurl = R.mipmap.tou7;
                break;
            case "8":
                newurl = R.mipmap.tou8;
                break;
            case "9":
                newurl = R.mipmap.tou9;
                break;
            case "10":
                newurl = R.mipmap.tou10;
                break;
            case "11":
                newurl = R.mipmap.tou11;
                break;
            case "12":
                newurl = R.mipmap.tou12;
                break;
            default:
                break;
        }
        return newurl;
    }
}